import hashlib
import os
from message import BotApi
from template import *
from mpclient import Client

from flask import Flask, request
from Panda.Core.Log import logger
from Panda.reply import check_msg


app = Flask(__name__)

app_secret = "638c985ec13f9fba369ecfa03e4137cf"
app_id = "wx38dfd6875798b877"
client = Client(app_id, app_secret)


def check_sign(data, token="hello"):
    signature = data.get("signature", "")
    echostr = data.get("echostr", "")
    timestamp = data.get("timestamp", "")
    nonce = data.get("nonce", "")
    logger.info(f"token:{token},signature:{timestamp},nonce:{nonce}")

    list1 = [token, timestamp, nonce]
    list1.sort()
    sh1 = hashlib.sha1()
    sh1.update("".join(list1).encode("utf-8"))
    hashcode = sh1.hexdigest()
    ret = echostr if hashcode == signature else "其他"
    return ret


@app.route("/", methods=["GET", "POST"])
def home():
    logger.info(request.method)
    if request.method == "GET":
        data = request.args
        logger.warning(request.data)
        logger.info(data)
        return check_sign(data)
    elif request.method == "POST":
        msg = BotApi(client, request.data.decode("utf-8"))
        logger.info(msg)
        admin = (
            True
            if msg.data_dict.fromUserName
            in ["oJVZ_6dz2BSHIUjiepXhTsivmTac", "oJVZ_6W7VgDPMUZgqRN3562XCiL4"]
            else False
        )
        xinxi = check_msg(msg, msg, admin, only_ret_txt=True)
        if os.path.exists(xinxi):
            media_id = msg.client.upload_file(xinxi)
            res = ImageResponse(MessageDict(msg.__dict__()), media_id, path=xinxi)
        else:
            res = TextResponse(MessageDict(msg.__dict__()), content=xinxi)
            article = Article(
                title="测试",
                description="这是一个测试",
                picurl="https://bkimg.cdn.bcebos.com/pic/2fdda3cc7cd98d1001e9c6524368af0e7bec54e73a02",
                url="https://bot.q.qq.com/wiki",
            )
            # res = NewsResponse(MessageDict(msg.__dict__()), article)
        logger.info(res)
        return res.to_xml


from gevent import pywsgi

if __name__ == "__main__":
    server = pywsgi.WSGIServer(("127.0.0.1", 80), app)
    logger.info("server start")
    server.serve_forever()
